package com.jboost.modules.app.service.strategry.xmallure;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.google.common.collect.Maps;
import com.google.gson.JsonObject;
import com.jboost.common.util.HttpRestUtils;
import com.jboost.common.util.JSONUtil;
import com.jboost.modules.app.constant.BaseResult;
import com.jboost.modules.app.constant.CustomerDetailInfo;
import com.jboost.modules.app.constant.CustomerInfo;
import com.jboost.modules.app.dto.JdyReq;
import com.jboost.modules.app.dto.XMUserAllureReqDto;
import com.jboost.modules.app.dto.XMUserReqDto;
import com.jboost.modules.app.dto.XmOrderPeople;
import com.jboost.modules.system.entity.AJdySyncData;
import lombok.extern.slf4j.Slf4j;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.apache.commons.compress.utils.Lists;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.http.HttpHeaders;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

//@Service(value = "xmFsAllureUserQuery")
@Slf4j
public class XmFsAllureUserQuery extends AbstractXmAllureUser<JsonObject, Boolean> {
    public String getAppId(){
        return "654318875348639588ec98ac";
    }

    @Async
    @Scheduled(cron = "0 0/10 * * * ?")
    public BaseResult<Boolean> invokeStrategy() throws Exception {
        log.info("开始批量查询客户数据");
        String header = getHeader("company");
        List<String> ids = Lists.newArrayList();
        queryAndPush(header, 1, ids);
        List<AJdySyncData> sysUserDeparts = gcDataMapper.selectList(Wrappers.lambdaQuery(AJdySyncData.class).notIn(AJdySyncData::getId, ids));
        for (AJdySyncData sysUserDepart : sysUserDeparts) {
            jdyDelete(sysUserDepart.getDataType());
        }
        return BaseResult.success();
    }




    public void queryAndPush(String header, Integer index, List<String> ids) throws Exception {
        HashMap<String, Object> paramMap = Maps.newHashMap();
        paramMap.put("start_index", index);
        paramMap.put("count", 20);
        HttpHeaders headers = new HttpHeaders();
        headers.set("Authorization", "Bearer " + header);

//        String s = HttpRestUtils.get("https://api-sandbox.xiaoman.cn/v1/company/fields", Maps.newHashMap(), headers);
//        System.out.println(s);
        //String custmorResponse = HttpRestUtils.get(customersUrl, paramMap, headers);
        OkHttpClient cclient = new OkHttpClient();
        Request request1 = new Request.Builder()
                .url(customersUrl + getParams(paramMap)).addHeader("Authorization", "Bearer " + header).get()
                .build();
        Response execute1 = cclient.newCall(request1).execute();
        String custmorResponse = execute1.body().string();
        CustomerInfo customerInfo = JSONUtil.fromJson(custmorResponse, CustomerInfo.class);
        customerInfo.getData().getList().forEach(e -> {
            long companyId = e.getCompany_id();
            ids.add(companyId + "");
            Map map = new HashMap();
            map.put("company_id", companyId);
            map.put("format", 0);
            try {
                HttpHeaders newHeaders = new HttpHeaders();
                newHeaders.set("Authorization", "Bearer " + header);
                OkHttpClient client = new OkHttpClient();
                Request request = new Request.Builder()
                        .url(customerDetailUrl + getParams(map)).addHeader("Authorization", "Bearer " + header).get()
                        .build();
                Response execute = client.newCall(request).execute();
                // String custmoerDetailResponse = HttpRestUtils.get(customerDetailUrl+getParams(map), map, newHeaders);
                // log.info("custmoerDetailResponse"+custmoerDetailResponse);
                String body = execute.body().string();
                CustomerDetailInfo customerDetailInfo = JSONUtil.fromJson(body, CustomerDetailInfo.class);
                AJdySyncData sysUserDepart = gcDataMapper.selectById(companyId + "");
                if (Objects.isNull(sysUserDepart)) {
                    addCustomer(customerDetailInfo);
                } else {
                    if (!Objects.equals(JSONUtil.toJson(customerDetailInfo.getData()),sysUserDepart.getData())) {
                        updateCustomer(sysUserDepart, customerDetailInfo);
                    }
                }
            } catch (IOException ex) {
                log.error("查询客户{}数据失败", companyId);
            }
        });
        if (CollectionUtil.isNotEmpty(customerInfo.getData().getList())) {
            queryAndPush(header, 1 + index, ids);
        }
    }

    public static String getParams(Map<String, Object> params) {
        StringBuffer sb = new StringBuffer("?");
        if (Objects.nonNull(params)) {
            for (Map.Entry<String, Object> item : params.entrySet()) {
                Object value = item.getValue();
                if (Objects.nonNull(value)) {
                    sb.append("&");
                    sb.append(item.getKey());
                    sb.append("=");
                    sb.append(value);
                }
            }
            return sb.toString();
        } else {
            return "";
        }
    }


    private void updateCustomer(AJdySyncData sysUserDepart, CustomerDetailInfo customerDetailInfo) throws IOException {
        HashMap<String, Object> param = getParam();
        XMUserAllureReqDto xmUserReqDto = buidXMUserReqDto(customerDetailInfo);
        param.put("data", xmUserReqDto);
        param.put("data_id", sysUserDepart.getDataType());
        String post = HttpRestUtils.post(update_api, param, jdyHeaders);
        sysUserDepart.setData(JSONUtil.toJson(customerDetailInfo.getData()));
        gcDataMapper.updateById(sysUserDepart);
        log.info("表单修改结果{}", post);
    }

    private XMUserAllureReqDto buidXMUserReqDto(CustomerDetailInfo customerDetailInfo) {
        XMUserAllureReqDto xmUserReqDto = new XMUserAllureReqDto();
        CustomerDetailInfo.DataBean data = customerDetailInfo.getData();
        List<CustomerDetailInfo.DataBean.CustomersBean> customers = data.getCustomers();
        //基本资料
        buildXmUserReqDtoBaseData(xmUserReqDto, customerDetailInfo);
        //运营联系人
        buildXmUserReqDtoData(xmUserReqDto, customers);
        return xmUserReqDto;
    }


    public String getFormId() {
        return "646b1bdd966dad0008cc3d5f";
    }

    private void buildXmUserReqDtoBaseData(XMUserAllureReqDto xmUserReqDto, CustomerDetailInfo customerDetailInfo) {
        CustomerDetailInfo.DataBean data = customerDetailInfo.getData();
        List<CustomerDetailInfo.DataBean.CompanyBean> company = data.getCompany();
        List<CustomerDetailInfo.DataBean.CompanyBean.FieldsBean> fieldsBeans = company.stream().flatMap(entry -> entry.getFields().stream()).collect(Collectors.toList());
        //fieldsBeans.addAll(customerDetailInfo.getData().getExternal_field_data());
        Map<String, String> fieldMap = fieldsBeans.stream().collect(Collectors.toMap(CustomerDetailInfo.DataBean.CompanyBean.FieldsBean::getId, CustomerDetailInfo.DataBean.CompanyBean.FieldsBean::getValue, (a, b) -> a));
        System.out.println(JSONUtil.toJson(fieldMap));
        xmUserReqDto.setCustomer_name(getParaMap(fieldMap.get("name")));
        xmUserReqDto.setCustomer_abbreviation(getParaMap(fieldMap.get("short_name")));
        String country = String.valueOf(getParaMap(fieldMap.get("country")));

        xmUserReqDto.setMonther_land(getParaMap(customerDetailInfo.getData().getCountry_name()));
        xmUserReqDto.setCustomer_no(getParaMap(customerDetailInfo.getData().getSerial_id()));
        List<XMUserReqDto.LogoBean> logoBeans = new ArrayList<>();
        XMUserReqDto.LogoBean logoBean = new XMUserReqDto.LogoBean();
        logoBean.setUrl(getParaMap(fieldMap.get("homepage")));
        logoBeans.add(logoBean);
        try {
            if (CollectionUtil.isNotEmpty(data.getOwner())) {
                JdyReq jdyReq = new JdyReq();
                jdyReq.setApp_id(getAppId());
                jdyReq.setEntry_id("66160a516c2efa24fea9bb93");
                jdyReq.setLimit(100);
                jdyReq.setFields(Arrays.asList("_widget_1712720465508", "_widget_1712720465507"));
                JdyReq.FilterBean filterBean = new JdyReq.FilterBean();
                filterBean.setRel("and");
                List<JdyReq.FilterBean.CondBean> cond = new ArrayList<>();
                JdyReq.FilterBean.CondBean a = new JdyReq.FilterBean.CondBean();
                a.setField("_widget_1712720465508");
                a.setType("text");
                a.setMethod("eq");
                a.setValue(Arrays.asList(data.getOwner().get(0).getNickname()));
                cond.add(a);
                filterBean.setCond(cond);
                jdyReq.setFilter(filterBean);

                String s = jdyQueryAll(jdyReq);
                JSONArray jsonArray = (JSONArray) JSONUtil.fromJson(s, HashMap.class).get("data");
                if (jsonArray.size() > 0) {
                    XmOrderPeople dataBean = JSONUtil.fromJson(JSONUtil.toJson(jsonArray.get(0)), XmOrderPeople.class);
                    xmUserReqDto.set_widget_1694629005949(getParaMap(dataBean.get_widget_1712720465507().getUsername()));
                }
            }
        } catch (IOException ex) {

        }

        HashMap<String, List<XMUserReqDto.LogoBean>> hashMap = Maps.newHashMap();
        hashMap.put("value", logoBeans);
    }

    private Object filterFh(Object country) {
        String s = country.toString();

        String replaceAll = s.replace("[", "").replace("]", "");
        String s1 = replaceAll.replaceAll("\"", "");
        return s1;
    }

    private void buildXmUserReqDtoData(XMUserAllureReqDto contact, List<CustomerDetailInfo.DataBean.CustomersBean> customers) {
        contact.setEmail(getParaMap(customers.stream().map(CustomerDetailInfo.DataBean.CustomersBean::getEmail).collect(Collectors.joining(","))));
    }

    private void addCustomer(CustomerDetailInfo customerDetailInfo) throws IOException {
        HashMap<String, Object> param = getParam();
        XMUserAllureReqDto xmUserReqDto = buidXMUserReqDto(customerDetailInfo);
        param.put("data", xmUserReqDto);
        String post = HttpRestUtils.post(add_api, param, jdyHeaders);
        HashMap hashMap = JSONUtil.fromJson(post, HashMap.class);
        log.info("表单新增结果{}", post);
        AJdySyncData userDepart = new AJdySyncData();
        userDepart.setId(customerDetailInfo.getData().getCompany_id() + "");
        userDepart.setDataType(((JSONObject) hashMap.get("data")).getString("_id"));
        userDepart.setData(JSONUtil.toJson(customerDetailInfo.getData()));
        gcDataMapper.insert(userDepart);

    }


}
